﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using LFSRecord2.Model;
using System.Diagnostics;
using LFSRecord2.Structures;
using LFSRecord2.Events;
using LFSRecord2.Model.Undo;
using LFSRecord2.Model.UserActions;
using LFSRecord2.View.TimelineStructures;

namespace LFSRecord2.View
{
    /// <summary>
    /// Interaction logic for KeylaneView.xaml
    /// </summary>
    public partial class KeylaneView : Canvas
    {
        public KeylaneView()
        {
            InitializeComponent();
        }

        private void KeyLane_LeftButtonMouseDown(object sender, MouseButtonEventArgs e)
        {
            //if (((CompLayerPropertyBase)DataContext).HasBoundProperty)
            //{
            //    return;
            //}

            //if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            //{
            //    e.Handled = true;

            //    // Add a keyframe
            //    Point curPoint = e.GetPosition(KeyCanvas);
            //    CompLayerPropertyBase prop = (CompLayerPropertyBase)DataContext;

            //    if (!Keyboard.IsKeyDown(Key.LeftShift))
            //        LFSRecordController.project.DeselectAll();

            //    CustomKeyFrame kf = prop.SetKeyAtCurrentTime((int)curPoint.X);
            //    kf.IsSelected = true;

            //    LFSRecordController.RecordUserAction(new UserActionAddKeyframe()
            //    {
            //        LayerIndex = kf.ParentLayer.LayerIndex,
            //        PropertyIndex = kf.ParentProperty.PropertyIndex,
            //        KeyFrame = kf.DataStructure()
            //    });
            //    LFSRecordController.CreateUndoLevel();
            //}
        }

        Point _startPoint;
        int _objectHasMoved = 0;
        bool _movedFirst = false;
        KeyImageControl _keyImage;
        private void KeyImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            _keyImage = (KeyImageControl)sender;
            CustomKeyFrame kf = (CustomKeyFrame)_keyImage.DataContext;

            _keyImage.IsHitTestVisible = false;

            if (!kf.IsSelected)
            {
                if (!Keyboard.IsKeyDown(Key.LeftShift) && !Keyboard.IsKeyDown(Key.RightShift))
                    LfsRecordController.project.DeselectAll();
                kf.IsSelected = true;
            }
            else
            {
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    kf.IsSelected = false;
                }
            }

            _startPoint = e.GetPosition(KeyCanvas);

            _movedFirst = false;
            _objectHasMoved = 0;

            Application.Current.MainWindow.MouseUp += KeyFrame_MouseUp;
            Application.Current.MainWindow.MouseMove += KeyFrame_MouseMove;
        }

        private void KeyFrame_MouseUp(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            Application.Current.MainWindow.MouseUp -= KeyFrame_MouseUp;
            Application.Current.MainWindow.MouseMove -= KeyFrame_MouseMove;

            _keyImage.IsHitTestVisible = true;
            _keyImage = null;

            if (_objectHasMoved != 0)
            {
                LfsRecordController.project.DeleteOverlappingKeyFrames();

                LfsRecordController.project.SubmitUserActionMoveSelectedKeyFrames(_objectHasMoved);
                LfsRecordController.project.SubmitUserActionMoveSelectedAudioRegions(_objectHasMoved / (double)LfsRecordController.project.FPS);
                LfsRecordController.CreateUndoLevel();
            }
            _objectHasMoved = 0;
            _movedFirst = false;

            //ServicesFactory.EventService.GetEvent<CompLayerPropertyChangedEvent>().Publish(new CompLayerPropertyChangedEventArgs() { Sender = this, PropertyType = "FrameNum", UpdateCurrentValues = true });
        }

        private void KeyFrame_MouseMove(object sender, MouseEventArgs e)
        {
            if (!_movedFirst)
            {
                _movedFirst = true;
                return;
            }

            //Debug.WriteLine("keyframe move");

            // Calculate the move offset
            Point curPoint = e.GetPosition(KeyCanvas);
            Point diff = new Point(curPoint.X - _startPoint.X, curPoint.Y - _startPoint.Y);

            // Get the x offset of the first selected KeyFrame
            double moveOffset = diff.X;
            if (moveOffset == 0)
                return;

            int firstFrameNum = LfsRecordController.project.GetFirstSelectedFrameNum();

            if (moveOffset < 0)
            {
                if (firstFrameNum <= 0)
                    return;
                if (firstFrameNum + moveOffset < 0)
                    moveOffset = -firstFrameNum;
            }
            _objectHasMoved += (int)moveOffset;
            //Debug.WriteLine("keyframe move - " + moveOffset + " - " + firstFrameNum);

            LfsRecordController.project.MoveSelectedAudioRegions(moveOffset / LfsRecordController.project.FPS);

            LfsRecordController.project.MoveSelectedKeyFrames((int)moveOffset);
            ServicesFactory.EventService.GetEvent<CompLayerPropertyChangedEvent>().Publish(new CompLayerPropertyChangedEventArgs() 
            { 
                Sender = this, 
                PropertyType = "FrameNum", 
                UpdateCurrentValues = true 
            });

            _startPoint = curPoint;
        }
    }
}
